#include "common.h"

int main(int argc, const char** argv)
{
    FILE* source_file;
    char source_name[MAX_FILE_NAME_LENGTH];
    char date[DATE_STRING_LENGTH];

    if(argc < 2)
	{
		printf("Usage: lister file\n");
		return 1;
	}

    source_file = init_lister(argv[1], source_name, date);
    
    while(get_source_line(source_file, source_name, date));

    return 0;
}

// Initializes the source_file_name, date string, and opens a file named by name for reading
FILE* init_lister(const char *name, char* source_file_name, char* date)
{
	time_t rawtime;
    struct tm* time_info;
    FILE* file;

    // Copy the file name to the source_file_name buffer
    strncpy(source_file_name, name, MAX_FILE_NAME_LENGTH);

    // Generate the time string
	time(&rawtime);
    time_info = localtime(&rawtime);
    strftime(date, DATE_STRING_LENGTH, "%a %b %d %T %Y", time_info);

    // Open the file for reading
    file = fopen(name, "r");

    return file;
}

// Gets one line of the src_file and echos it to the output
BOOLEAN get_source_line(FILE* src_file, const char* src_name, const char* todays_date)
{
    char source_buffer[MAX_SOURCE_LINE_LENGTH];
    static int line_number = 0;

    fgets(source_buffer, MAX_SOURCE_LINE_LENGTH, src_file);
	++line_number;
    print_line(source_buffer, src_name, todays_date, line_number);
    
    // If the file end has not been reached
    if(!feof(src_file))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

